import os.path
import subprocess
from convert import Conversion
from scipy.io import wavfile
import shutil

class Model:

    def __init__(self):
        self.files = []
        self.effects = []
        self.convert = Conversion()
        self.code = {"Decimator":"DEC", "Bitcrusher":"BIT", "Delay":"DLY",
                     "Echo":"ECO", "Bitwise KO":"BKO", "Lowpass":"LPF",
                     "Hightpass":"HPF", "Bandpass": "BPF", "Notch":"NPF"}
        self.fx = {"fx1":{"effect":"Bitwise KO", "slot1":"AND", "slot2":"XOR"},
                   "fx2":{"effect":"Decimator", "slot1":"Range", "slot2":"Rate"}}
        self.configEffects = {"Decimator":["Range", "Rate"], "Bitcrusher":["Range", "Rate"],
                         "Delay":["Delay", "Length"], "Echo":["Delay", "Length"],
                         "Bitwise KO":["AND", "XOR"],
                         "Lowpass":[], "Hightpass": [], "Bandpass": [], "Notch":[]}
        self.loopGrid = {"1":{"fraction":0.5, "hl":"latch", "sample":""},
                         "2":{"fraction":0.5, "hl":"latch", "sample":""},
                         "3":{"fraction":0.5, "hl":"latch", "sample":""},
                         "4":{"fraction":0.5, "hl":"latch", "sample":""},
                         "5":{"fraction":0.5, "hl":"latch", "sample":""},
                         "6":{"fraction":0.5, "hl":"latch", "sample":""},
                         "7":{"fraction":0.5, "hl":"latch", "sample":""},
                         "8":{"fraction":0.5, "hl":"latch", "sample":""},
                         "9":{"fraction":0.5, "hl":"latch", "sample":""},
                         "10":{"fraction":0.5, "hl":"latch", "sample":""},
                         "11":{"fraction":0.5, "hl":"latch", "sample":""},
                         "12":{"fraction":0.5, "hl":"latch", "sample":""},
                         "13":{"fraction":0.5, "hl":"latch", "sample":""},
                         "14":{"fraction":0.5, "hl":"latch", "sample":""},
                         "15":{"fraction":0.5, "hl":"latch", "sample":""},
                         "16":{"fraction":0.5, "hl":"latch", "sample":""},
                         }

    def addFile(self, location):
        filename = self.convert.convertFile(location)
        if filename in self.files:
            print "File Replaced"
        elif filename == None:
            print "Bad File"
        else:
            self.files.append(filename)
        return filename

    def changeEffects(self, fx):
        self.fx = fx

    def setGridOption(self, grid, fraction, option, sample):
        if fraction == "":
            fraction = "0.5"
        if option == "":
            option = "hatch"
        self.loopGrid[grid] = {"fraction": fraction, "hl": option, "sample":sample}
        
    def removeFile(self, location):
        self.files.remove(location)

    def getAudio(self, location):
        return wavfile.read(location)

    def getFiles(self):
        return self.files

    def getFilenames(self):
        names = []
        for location in self.files:
            names.append({os.path.split(location)[1]:location})
        return names
    
    def getFile(self, filename):
        for location in self.files:
            if os.path.split(location)[1] == filename:
                return location

    def setFile(self, files):
        self.files = files

    def getEffects(self):
        return self.effects

    def getEffectsList(self):
        return self.configEffects.keys()

    def setEffects(self, effects):
        self.effects = effects

    def parseEffects(self):
        output = ""
        output = output + "FX1=%s\n" % self.code[self.fx["fx1"]["effect"]]
        output = output + "FX2=%s\n" % self.code[self.fx["fx2"]["effect"]]
        return output

    def parseGrid(self):
        output = ""
        hl = ""
        fraction = ""
        for button in sorted(self.loopGrid, key=lambda key: self.loopGrid[key]):
            print self.loopGrid[button]["fraction"]
            fraction = int(1/float(self.loopGrid[button]["fraction"]))
            if fraction < 10:
                fraction = "0%d" % fraction
            elif fraction >= 10:
                fraction = "%d" % fraction
            output = output + "BT%sF=%s\n" % (hex(int(button))[2], fraction)
            if self.loopGrid[button]["hl"] == "hatch":
                hl = "h"
            elif self.loopGrid[button]["hl"] == "latch":
                hl = "l"
            output = output + "BT%sHL=%s\n" % (hex(int(button))[2], hl)
        return output

    def saveConfiguration(self, path):
        fp = open(os.path.normpath(os.path.join(path, "mpc.conf")), "w")
        fp.write(self.parseEffects())
        fp.write(self.parseGrid())
        fp.close()

    def transfer(self, path, files):
        self.saveConfiguration(path)
        self.copyAudio(path, files)

    def getParameters(self, value):
        return self.configEffects[value]

    def copyAudio(self, path, files):
        print path
        for item in files:
            #location = self.getFile(item)
            print item
            shutil.copy(item, os.path.normpath(path))

    def TransferAudio(self, path):
        self.saveConfiguration(path)
        for button in self.loopGrid.keys():
            print self.loopGrid[button]["sample"]
            newname = self.loopGrid[button]["sample"]
            outputFile = os.path.normpath(os.path.join(os.path.dirname(__file__), "../audio/%s" % newname))
            print outputFile
            shutil.copy(outputFile, os.path.join(os.path.normpath(path), "%s.wav" % button))
        

    
        
        
